package com.woniuxy.cloud.carl.store.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.carl.order.client.ServiceQueryClient;
import com.woniuxy.cloud.carl.order.client.result.ServiceDetailDto;
import com.woniuxy.cloud.carl.store.client.param.*;
import com.woniuxy.cloud.carl.store.client.result.StoreDto;
import com.woniuxy.cloud.carl.store.common.StoreStateEnum;
import com.woniuxy.cloud.carl.store.infra.model.Attachment;
import com.woniuxy.cloud.carl.store.infra.model.Store;
import com.woniuxy.cloud.carl.store.infra.mapper.StoreMapper;
import com.woniuxy.cloud.carl.store.service.AttachmentService;
import com.woniuxy.cloud.carl.store.service.StoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.cloud.carl.store.service.StoreServiceService;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.CommonResultCodeEnum;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2023-07-19
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {
    @Autowired
    AttachmentService attachmentService;
    @Autowired
    StoreServiceService storeServiceService;
    @Autowired
    ServiceQueryClient serviceQueryClient;
    @Override
    public Result addStore(AddStoreParam param) {
        if (param.getStartTime().compareTo(param.getEndTime())>0)
            throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"开始营业时间不能晚于结束营业时间");
        Store store1 = getOne(new QueryWrapper<Store>().eq("store_phone", param.getStorePhone()));
        if (store1!=null)throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"该门店已存在");
        Store store = BeanUtil.copyProperties(param, Store.class);
        store.setCreateTime(new Date());
        store.setGrade(5.0);
        store.setStoreState(StoreStateEnum.STORE_OFF.getCode());
        save(store);
        for (String attachment : param.getAttachments()) {
            Attachment attachment1 = new Attachment();
            attachment1.setPath(attachment);
            attachment1.setStoreId(store.getStoreId());
            attachmentService.save(attachment1);
        }
        for (Long serviceId : param.getServiceIds()) {
            com.woniuxy.cloud.carl.store.infra.model.StoreService storeService = new com.woniuxy.cloud.carl.store.infra.model.StoreService();
            storeService.setStoreId(store.getStoreId());
            storeService.setServiceId(serviceId);
            storeServiceService.save(storeService);
        }
        return Result.success();
    }

    @Override
    public Result modifyStore(ModifyStoreParam param) {
        if (param.getStartTime()!=null&&param.getEndTime()!=null){
            if (param.getStartTime().compareTo(param.getEndTime())>0)
                throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"开始营业时间不能晚于结束营业时间");
        }
        Store store1 = getOne(new QueryWrapper<Store>().eq("store_phone", param.getStorePhone()));
        if (store1!=null)throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"该电话已被使用");
        Store store = BeanUtil.copyProperties(param, Store.class);
        updateById(store);
        return Result.success();
    }

    @Override
    public Result modifyStorePassword(ModifyStorePasswordParam param) {
        Store store = getById(param.getStoreId());
        if (store==null) throw new MallException(CommonResultCodeEnum.DATA_NOT_FOUND,"该门店不存在");
        if (!store.getStorePassword().equals(param.getStorePassword()))
            throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"密码错误");
        store.setStorePassword(param.getNewStorePassword());
        updateById(store);
        return Result.success();
    }

    @Override
    public Result modifyStoreState(ModifyStoreStateParam param) {
        StoreStateEnum storeState = StoreStateEnum.getStoreState(param.getState());
        if (storeState==null) throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"状态信息错误");
        if (param.getState()==StoreStateEnum.STORE_DISAPPEAR.getCode())
            attachmentService.remove(new QueryWrapper<Attachment>().eq("store_id",param.getStoreId()));
        Store store = new Store();
        store.setStoreId(param.getStoreId());
        store.setStoreState(param.getState());
        boolean b = updateById(store);
        if (b) return Result.success(CommonResultCodeEnum.SUCCESS,"修改状态成功",null);
        return Result.fail("修改状态失败");
    }

    @Override
    public Result<List<StoreDto>> getStore(GetStoreParam param) {
        ArrayList<StoreDto> storeDtos = new ArrayList<>();
        List<Store> stores = new ArrayList<>();
        if (param.getStoreId()!=null){
            Store store = getById(param.getStoreId());
            Assert.state(store!=null,"门店信息错误");
            stores.add(store);
        }else if ((param.getCondition()!=null&&!param.getCondition().equals(""))||param.getState()!=null){
            QueryWrapper<Store> wrapper = new QueryWrapper<>();
            if (param.getState()!=null)
            wrapper.eq("store_state",param.getState());
            if (param.getCondition()!=null&&!param.getCondition().equals(""))
            wrapper.like("store_addr",param.getCondition()).or().like("store_name",param.getCondition());
            stores = list(wrapper);
        }else {
            stores = list();
        }
        Assert.state(stores!=null,"查询结果为空");
        for (Store store : stores) {
            StoreDto storeDto = BeanUtil.copyProperties(store, StoreDto.class);
            List<Attachment> attachments = attachmentService.list(
                    new QueryWrapper<Attachment>().eq("store_id", store.getStoreId()));
            List<String> stringList = attachments.stream().map(o -> o.getPath()).collect(Collectors.toList());
            storeDto.setAttachments(stringList);
            StoreStateEnum storeState = StoreStateEnum.getStoreState(store.getStoreState());
            storeDto.setStoreStateName(storeState.getState());
            List<com.woniuxy.cloud.carl.store.infra.model.StoreService> serviceList
                    = storeServiceService.list(new QueryWrapper<com.woniuxy.cloud.carl.store.infra.model.StoreService>()
                    .eq("store_id", store.getStoreId()));
            List<Long> list = serviceList.stream().map(o -> o.getServiceId()).collect(Collectors.toList());
            storeDto.setServiceIds(list);
            storeDtos.add(storeDto);
        }
        return Result.success(storeDtos);
    }

    @Override
    public Result<Long> storeLogin(StoreLoginParam param) {
        Store store = getOne(new QueryWrapper<Store>().eq("store_phone", param.getStorePhone()));
        Assert.state(store!=null,"账号或密码错误");
        if(!store.getStorePassword().equals(param.getStorePassword()))
            throw new MallException(CommonResultCodeEnum.FAIL,"账号或密码错误");
            return Result.success(CommonResultCodeEnum.SUCCESS,"登录成功",store.getStoreId());
    }
    @Override
    public Result modifyServiceInStore(AddServiceInStoreParam param) {
        List<com.woniuxy.cloud.carl.store.infra.model.StoreService> storeServices = storeServiceService.list(
                new QueryWrapper<com.woniuxy.cloud.carl.store.infra.model.StoreService>()
                .eq("store_id", param.getStoreId()).in("service_id", param.getServiceIds()));
        //System.out.println(storeServices.size());
        Assert.state(storeServices==null,"请勿重复添加服务");
        Store store = getById(param.getStoreId());
        Assert.state(store!=null,"门店信息错误");
        //新增
        if (param.getDoWhat()==1){
            for (Long serviceId : param.getServiceIds()) {
                //调用服务接口查询服务是否存在
                Result<ServiceDetailDto> serviceDetail = serviceQueryClient.findServiceDetail(serviceId);
                Assert.state(serviceDetail.getData()!=null,"服务信息错误");
                com.woniuxy.cloud.carl.store.infra.model.StoreService storeService = new com.woniuxy.cloud.carl.store.infra.model.StoreService();
                storeService.setServiceId(serviceId);
                storeService.setStoreId(param.getStoreId());
                storeServiceService.save(storeService);
            }
        }
        //删除
        else {
            QueryWrapper<com.woniuxy.cloud.carl.store.infra.model.StoreService> wrapper = new QueryWrapper<>();
            wrapper.eq("store_id",param.getStoreId()).in("service_id",param.getServiceIds());
            storeServiceService.remove(wrapper);
        }
        return Result.success();
    }

    @Override
    public Result<List<Long>> getServiceByStoreId(Long storeId) {
        List<com.woniuxy.cloud.carl.store.infra.model.StoreService> storeServiceList = storeServiceService.list(new QueryWrapper<com.woniuxy.cloud.carl.store.infra.model.StoreService>().eq("store_id", storeId));
        List<Long> longList = storeServiceList.stream().map(o -> o.getServiceId()).collect(Collectors.toList());
        return Result.success(longList);
    }
}
